import React, { Component } from 'react'

import SelectInput from './SelectInput'
import CheckboxNumber from './CheckboxNumber'
import Table from './Table'

import { myAjaxJson, myAjaxText, getAuthShop, ROOTURL } from '../publicAPI/publicAPI'

import '../css/SchedulingM.css'

class SchedulingM extends Component {
	constructor (props, context) {
	    super(props, context)

	    this.state = {
				  select_show: "none",
          timeHint: {show: "none", msg: "保存成功"},
          shops: [],
          timeTable: 'none',
          barbers: [],
          shopDate: []
			} // 初始化状态

      //类变量
      this.nowTime = null;             //当前选中的时间
      this.dateLen = -1;               //一天上班的时间段
      this.dateSort = [];              //选中的排版时间段
      this.addDateSort = [];           //添加的排版时间段
      this.cutDateSort = [];           //删除的排版时间段
      this.barber = null;              //当前理发师
      this.barberSeg = [];             //当前理发师排版
	}

	componentWillMount() {
			getAuthShop({where: {
				  stActivate: [
						  ['eq', true]
					]
			}}, (data) => {
				this.getShops(data);
			});
			this.selectTime = this.timeSelect();
	}

/*=========================================================shop start================================================*/
  //获取所有门店
  getShops(data) {
      let shops = [];
      for (let shop of data) {
          shops.push({
              id: shop.id,
              name: shop.dname,
              tmOpen: shop.tmOpen,
              tmClose: shop.tmClose
          });
      }
      this.setState({
          shops: shops
      })
  }
  /*----------------------------------------------------------------------------
  | 选择门店
    ----------------------------------------------------------------------------
  */
	inputTClick(id, txt) {
      this.refs.select_in.value = txt;
			this.setState({
				  select_show: "none",
          timeTable: 'block',
          timeHint:{
              show: "none"
          }
			})

			//根据选择的门店ID 初始化页面数据
      this.tTimeBody(id);
      this.getShopBarber(id);
	}
  //显示门店
  inputFocus() {
      this.setState({
          select_show: "block"
      })
  }
/*=========================================================shop end================================================*/

/*=========================================================barber start================================================*/
  /*----------------------------------------------------------------------------
  | 获取当前门店 理发师
    ----------------------------------------------------------------------------
  */
  getShopBarber(id) {
      myAjaxJson(ROOTURL + 'servant/profile/search.api', 'POST', {
        where:{
            dd:[
                ["eq", false]
            ],
            stActivate:[
                ["eq", true]
            ],
            shopId:[
                ["eq", id]
            ]
      }}, function(data) {
          const barbers = [];
          if (data.length > 0) {
              data.forEach(function(barber) {
                   barbers.push({
                       id: barber.id,
                       name: barber.meta.name
                   });
              })
              this.barber = barbers[0];
              this.getBarberServices(this.barber.id);
              this.setShedual(this.nowTime);
          } else {
              this.setState({
                   timeTable: 'none'
              })
              alert("请为门店分配理发师")
          }
          this.setState({
               barbers
          })
      }.bind(this))
  }
  //选择理发师
  selectingBarber(value) {
      const barbers = this.state.barbers;
      this.setState({
          timeHint:{
              show: "none"
          },
          timeTable: 'block'
      })
      this.barber = barbers.find(function(b) {
          return b.id == value;
      })
      this.getBarberServices(this.barber.id);
      this.setShedual(this.nowTime);
  }
  //判断当前理发师有无分配服务类型
  getBarberServices(id) {
      myAjaxJson(ROOTURL + 'serv/concrete/aggregated/search.api', 'POST', {
        where:{
            servantId:[
                ["eq", id]
            ]
      }}, function(data) {
          if (data.length <= 0) {
              this.setState({
                   timeTable: 'none'
              })
              alert("请为理发师分配服务！")
          }
      }.bind(this))
  }
/*=========================================================barber end================================================*/

/*=========================================================update timeTable start================================================*/
  /*----------------------------------------------------------------------------
  | 更新当前 理发师排版
    ----------------------------------------------------------------------------
  */
  updateBarberSeg(sorts) {
      this.barberSeg = [];
      for(let i = 0, l = this.dateLen * 7; i < l; i++) {
          if (sorts.indexOf(i) !== -1) {
              this.barberSeg.push(true);
          } else {
              this.barberSeg.push(false);
          }
      }
      this.setState({
          shopDate: this.state.shopDate
      })
  }

  /*----------------------------------------------------------------------------
  | 初始化 当前 理发师排版
    ----------------------------------------------------------------------------
  */
  setShedual(time) {
      if (!this.barber) return;
      let dates = time.split(" - ");
      let f     = new Date(dates[0]).getTime();
      let t     = new Date(dates[1]).getTime() + 24*60*60*1000;
      myAjaxJson(ROOTURL + 'servant/schedule/segment/search.api', 'POST', {
          where: {
              servantId: [
                  ["eq", this.barber.id]
              ],
              f: [
                  ["ge", f]
              ],
              t: [
                  ["le", t]
              ]
          }
      }, function(data) {
          this.tranMsToCheckbox(data);
      }.bind(this))

  }
  /*------------------------------------------------------------------------
  | 将理发师排版的毫秒数 转换为日期的时间段
   -------------------------------------------------------------------------
  */
  tranMsToCheckbox(segments) {
      this.dateSort = [];
      this.cutDateSort = [];
      this.addDateSort = [];
      segments.forEach(function(seg) {
          let start = this.tranDateToNumber(new Date(seg.f), 0);
          let end   = this.tranDateToNumber(new Date(seg.t), 1);
          for( let i = start; i<=end; i++ ) {
              this.dateSort.push(i);
          }
      }.bind(this));
      this.updateBarberSeg(this.dateSort);
  }

  tranDateToNumber(date, pOrc) {
      let line = date.getDay() - new Date(this.nowTime.split(' - ')[0]).getDay();
      let openHour = + this.state.shopDate[0].split(":")[0];
      let row = date.getHours() - openHour - pOrc;
      return line*this.dateLen + row;
  }

/*=========================================================update timeTable end================================================*/

/*=========================================================星期 start================================================*/
  //改变当前排班日期
  scheduleDateChange(val) {
      this.nowTime = val;
      this.setShedual(val);
      this.setState({
          timeHint:{
              show: "none"
          }
      })
  }
  /*--------------------------------------------------------------------------
  | 格式化时间2016/07/24
   ---------------------------------------------------------------------------
  */
  formatTime(date) {
      return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
  }

  timeSelect() {
      let date = new Date();
      let W  = date.getDay();
      let times = [];
      let d = '';
      for( let i = 0; i < 4; i ++ ){
          if (i !== 0) {
              date.setDate(date.getDate() + 1);
          } else {
              date.setDate(date.getDate() - W);
          }
          d += this.formatTime(date);
          date.setDate(date.getDate() + 6);
          d += ' - ' + this.formatTime(date);
          times.push(d);
          d = '';
      }
      this.nowTime = times[0]
      return times;
  }

/*=========================================================星期 end================================================*/


/*=====================================================time table ===================================================*/
  /*----------------------------------------------------------------------------
  | 门店服务时间头部设置 表格
    ----------------------------------------------------------------------------
  */
  tTimeHead() {
      const _date = ['日', '一', '二', '三', '四', '五', '六']
      const _tHeadArr = [];
      _tHeadArr.push(<th style={{width:"16%"}} key={0}></th>);
      for(let i = 0; i < _date.length; i++ ) {
          _tHeadArr.push(<th style={{width:"12%"}} key={i + 1}>{_date[i]}</th>)
      }

      return _tHeadArr;
  }

	/*----------------------------------------------------------------------------
	| 门店服务时间内容设置 表格
		----------------------------------------------------------------------------
	*/
	tTimeBody(id) {
      let nowShop  = this.state.shops.find(function(shop) {
          return shop.id === id;
      });
      let shopDate = this.tranMsToHour(nowShop.tmOpen, nowShop.tmClose);
      this.dateLen = shopDate.length;
      this.barberSeg = new Array(this.dateLen*7).fill(false);
			this.setState({
          shopDate
      })
	}

  /*------------------------------------------------------------------------------
  |根据传入门店开始时间 和 门店关闭时间生成理发师排版时间列表
  |传入时间格式为 毫秒数
   -------------------------------------------------------------------------------
  */
  tranMsToHour(tmOpen, tmClose) {
      let _date = [];
      let toHourO = Math.floor(tmOpen / 1000 / 60 / 60);
      let half = (tmOpen /1000 / 60 % 60 ) >= 30? ":30": ":00";
      let toHourC = Math.floor(tmClose / 1000 / 60 / 60);
      for(let s = toHourO; s < toHourC; ){
          let Op = (s > 9? s : '0' + s) + half;
          s++;
          let Cl = (s > 9? s : '0'+ s) + half;
          _date.push(Op + ' - ' + Cl);
      }
      return _date;
  }
/*=====================================================time table end ===================================================*/


/*=====================================================删除，添加排版控制  start===============================================*/
  // 选择时间
  selectCheckbox(check, number) {
      if (check) {
					let cut = this.cutDateSort.indexOf(number);
					if (cut > 0) {
					    this.cutDateSort.splice(cut, 1)
					}
					if (this.dateSort.indexOf(number) === -1) {
						  this.addDateSort.push(number);
							this.dateSort.push(number);
					}
      } else if (!check) {
				  let add = this.addDateSort.indexOf(number);
					let ds  = this.dateSort.indexOf(number);
					if (add > 0) {
					    this.addDateSort.splice(add, 1)
					}
					if ( ds !== -1) {
						  this.cutDateSort.push(number);
							this.dateSort.splice(ds, 1);
					}
      }
			this.barberSeg[number] = check;
			this.setState({
				  timeHint:{
						 show: "none"
				  }
		  })
  }
  selectAllShedule() {
      this.cutDateSort = [];
      this.dateSort = [];
      this.addDateSort = [];
      this.barberSeg = new Array(this.dateLen*7).fill(true);
      for(let i = 0, l = this.dateLen * 7; i < l; i++) {
          this.dateSort.push(i);
          this.addDateSort.push(i);
      }
      this.setState({
          shopDate: this.state.shopDate
      })
  }
	delAllShedule() {
			this.cutDateSort = [];
			this.dateSort = [];
			this.addDateSort = [];
			this.barberSeg = new Array(this.dateLen*7).fill(false);
			for(let i = 0, l = this.dateLen * 7; i < l; i++) {
					this.cutDateSort.push(i);
			}
			this.setState({
					shopDate: this.state.shopDate
			})
	}

  saveTimeSchadule() {
      if (!this.barber) {
          alert("请先为门店分配理发师！");
          return;
      }
      // 添加排班
      this.changeTimeShedule(this.addDateSort, 'servant/schedule/segment/instance.api', 1);
      // 删除排班
      this.changeTimeShedule(this.cutDateSort, 'servant/schedule/segment/subtract.api', 0);
			this.addDateSort = [];
			this.cutDateSort = [];
  }

  //保存排版
  changeTimeShedule(dateSort, url, flag) {
      const time = new Date(this.nowTime.split(" - ")[0]).getTime();
      let cutDate = this.handleSelectDate(dateSort);
			this.pushToServer(cutDate, time, url, flag);
  }
	pushToServer(cutDate, time, url, flag) {
		  if(cutDate.length > 0) {
				    let date = cutDate.shift();
						let f = time + this.exactTime(date[0], true);
						let t = time + this.exactTime(date[date.length -1]);
						myAjaxText(ROOTURL + url, 'POST', {
								servant: this.barber.id,
								f: f,
								t: t
						}, function() {
							  this.pushToServer(cutDate, time, url, flag);
								this.setState({
										timeHint:{
												show: "block",
												msg: "保存成功"
										}
								})
						}.bind(this), function() {
						  	this.pushToServer(cutDate, time, url, flag);
								this.updateViewTimeShedule(date, flag);
								this.setState({
										timeHint:{
												show: "block",
												msg: "保存失败"
										}
								})
						}.bind(this))
			}
	}
  updateViewTimeShedule(date, flag) {
		  const _this = this;
      if (flag == 0) {
          this.dateSort.concat(date);
      } else {
				date.forEach(function(d) {
					  let index = _this.dateSort.indexOf(d);
						if (index != -1) _this.dateSort.splice(index, 1);
				});
      }
      this.updateBarberSeg(this.dateSort);
  }
  /*------------------------------------------------------------------------------
  | 处理创建理发师排版时 选中的时间段
   -------------------------------------------------------------------------------
  */
  handleSelectDate(dates) {
		  let len = this.dateLen;
      let cutDates = [];
      let now = [];
      dates.sort(function(a, b) {
          return a - b;
      });
      dates.forEach(function(date, i) {
				  if (date - dates[i + 1] === -1) {
						  now.push(date);
						  if (dates[i + 1] != 0 && dates[i + 1] % len == 0) {
									cutDates.push(now);
									now = [];
							}
          } else {
              now.push(date);
              cutDates.push(now);
              now = [];
          }
      });

      return cutDates;
  }
  exactTime(t, pn) {
      const len  = this.dateLen;
      let week = Math.floor(t/len);
      let d    = t % len;
      let hh = pn ? this.state.shopDate[d].split(' - ')[0] : this.state.shopDate[d].split(' - ')[1];
      hh = hh.split(":");
      return (week * 24 * 60 + (+hh[0]) * 60 + (+hh[1])) * 60 * 1000;
  }
/*=====================================================删除，添加排版控制  end===============================================*/

  render() {
      const that = this;
	    return (
					<div className="right-wapper">
						  <div className="rt-wrap rt-wrap-header">
  					    	<div className="input-div pr">
      								<label>门店：</label>
      								<input ref="select_in" type="text" placeholder="请选择门店" className="default-text"
      									onFocus={this.inputFocus.bind(this)} />
      								<ul className="input_select" style={{display: this.state.select_show}}>
      									   { this.state.shops.map((value, index) => {
                               return <li key={index} value={value.id} onClick={this.inputTClick.bind(this, value.id, value.name)}>{value.name}</li>
                           })}
      								</ul>
  						    </div>

    							<div className="input-div">
      								<label>日期:</label>
      								<SelectInput onChange={this.scheduleDateChange.bind(this)} optionsData={ this.selectTime.map(function(time, index){
                          return <option key={index}>{time}</option>
                      })} />
    							</div>

    							<div className="input-div">
      								<label>理发师:</label>
      								<SelectInput onChange={this.selectingBarber.bind(this)} optionsData={this.state.barbers.map((value, index) => {
                          return <option key={index} value={value.id}>{value.name}</option>
                      })}/>
    							</div>
						  </div>

  						<div className="rt-wrap" style={{display: this.state.timeTable}}>
                  <p className="hintMessage" style={{display: this.state.timeHint.show}}>{this.state.timeHint.msg}</p>
  						  	<h3 className="catagory">
  							    	<span className="cata-title">理发师排班表</span>
                      <button onClick={this.saveTimeSchadule.bind(this)}>保存</button>
											<button onClick={this.selectAllShedule.bind(this)}>全选</button>
                      <button onClick={this.delAllShedule.bind(this)}>反选</button>
  							  </h3>
    							<Table tBody={this.state.shopDate.map((date, index) => {
                    return <tr key={index} className={"shopTimeTable"}>
                               <td>{date}</td>
                               <td><CheckboxNumber number={index} isCheck={that.barberSeg[index]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen} isCheck={this.barberSeg[index + this.dateLen]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen*2} isCheck={this.barberSeg[index + this.dateLen*2]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen*3} isCheck={this.barberSeg[index + this.dateLen*3]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen*4} isCheck={this.barberSeg[index + this.dateLen*4]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen*5} isCheck={this.barberSeg[index + this.dateLen*5]} onChange={this.selectCheckbox.bind(this)} /></td>
                               <td><CheckboxNumber number={index + this.dateLen*6} isCheck={this.barberSeg[index + this.dateLen*6]} onChange={this.selectCheckbox.bind(this)} /></td>
                           </tr>
                  })} tHead={this.tTimeHead.bind(this)()}/>
  						</div>
					</div>
	    )
	}
}

export default SchedulingM
